package at.catalysts.imgClassifier.dataFinders;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import at.jaki.ubb.crawling.api.DataFinder;
import at.jaki.ubb.crawling.model.DataFinderResult;
import at.jaki.ubb.crawling.model.Target;
import at.jaki.ubb.crawling.stlib.dataFinder.SimpleHttpClient;

public class TextReader implements DataFinder<String, String, String> {

	public static final String INPUT_TYPE_TEXT = "textFile";

	public DataFinderResult<String, String> findData(Target<String> t) {
		File f = new File(t.getValue());

		Collection<Target<String>> targetCollection = new ArrayList<Target<String>>();
		DataFinderResult<String, String> dfr = new DataFinderResult<String, String>(null, targetCollection);

		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				sb.append(' ');
				line = br.readLine();
			}
			Pattern pt = Pattern.compile("http:\\S+");
			Matcher m = pt.matcher(sb.toString());
			while (m.find()) {
				String url = m.group(0);
				targetCollection.add(new Target<String>(0.9D, url, SimpleHttpClient.INPUT_TYPE, url));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return dfr;
	}

	public void init() {

	}

	public Collection<String> getTypes() {
		return Collections.singletonList(INPUT_TYPE_TEXT);
	}

}
